import React, {Component} from 'react';
import {Platform,Linking,StatusBar,DeviceEventEmitter,StyleSheet,TouchableOpacity,TextInput,Text,Image,Button,Alert,FlatList,PermissionsAndroid,View} from 'react-native';
import { MapView,Geocode,Location } from 'react-native-baidumap-sdk'
import{connect} from 'react-redux' 
import Toast from 'react-native-root-toast'; 
import Modal from "react-native-modal";
import NET from '../util/netUtil'
import {SERVER} from '../util/config'
import * as NaviCtl from '../util/naviConvert'
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";



const { Marker, Callout } = MapView




class map extends Component{
   
    constructor(props){
        super(props);
       this.state={   
           Slocation:{},
           lastlat:31.9083466555,
           lastlon: 117.54,
           speed:0,
           logs: [],
           points:[],
           enableLocation:true,  
           isNaviShow:false,
           isMoldeShow:false
       }
    //Toast.show("Debug-in");
    // Initializer.init('ymhzfCdDEbSyRTV2jaa8sncLfQ5nWP74').catch(e => console.error(e));
      
       this.getMachineByCity=this.getMachineByCity.bind(this);
       this.getMachineNearMe=this.getMachineNearMe.bind(this);
       this._points; 
       this.province="安徽";
       this.city="合肥市";
       this.district="肥东";
       this.zoomLevel=10;
       this.lastLat=undefined;
       this.lastLon=undefined;
       this._mapView;
       this.targetLat;
       this.targetLon;
       this.glocation={latitude:31.91316, longitude:117.55082};
       this.firstUse=true;
    }

   

    static navigationOptions = {
     header:null
    };

    _log(event, data) {
        this.setState({
          logs: [
            {
              key: Date.now(),
              time: new Date().toLocaleString(),
              event,
              data:data.speed.toFixed(2)*3.6, //JSON.stringify(data.speed, null, 2),
            },
            ...this.state.logs,
          ],
        })

       
      }


      async requestLocationPermission() {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '请求定位权限',
                    'message': '用于查找附近仪器'
                }
            )

            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                Toast.show("你已获取了定位权限")

            } else {
               Toast.show("没有获取定位权限")

            }
        } catch (err) {
           console.log(err.toString())
        }
    }


    reverseCity = async coordinate => {
        const reverseResult = await Geocode.reverse(coordinate);
        this.province=reverseResult.province;
        this.city=reverseResult.city;
        this.district=reverseResult.district;
        this.getMachineByCity(this.city);
        this.firstUse=false;
        //this.setState(result)
        //this.marker.select()
      }

      
async componentDidMount() {


    

    this.requestLocationPermission(); 

    await Location.init();
    Location.setOptions({ distanceFilter:0,gps:false })
    this.listener=Location.addLocationListener(location => {

       //Toast.show(JSON.stringify(location));
        //
       // Alert.alert("Get GPS data");

        this.glocation=location
        this.setState({Slocation:location})
        this.lastLat=location.latitude;
        this.lastLon=location.longitude;
        //Toast.show(location.speed);
        this.setState({lastlat:location.latitude});
        this.setState({lastlon:location.longitude});
        if( this.firstUse)
        { 
            this.reverseCity({latitude: this.lastLat, longitude: this.lastLon});
        }
     
    
    });
   

    LocationServicesDialogBox.checkLocationServicesIsEnabled({
        message: "<h2 style='color: #0af13e'>使用位置服务?</h2>App需要更改设备设置:<br/><br/>使用 GPS, Wi-Fi,或移动网络进行定位<br/><br/>",
        ok: "是",
        cancel: "否",
        enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => GPS OR NETWORK PROVIDER
        showDialog: true, // false => Opens the Location access page directly
        openLocationServices: true, // false => Directly catch method is called if location services are turned off
        preventOutSideTouch: false, // true => To prevent the location services window from closing when it is clicked outside
        preventBackClick: false, // true => To prevent the location services popup from closing when it is clicked back button
        providerListener: false // true ==> Trigger locationProviderStatusChange listener when the location state changes
    }).then(function(success) {
       
        Toast.show("GPS OK");
       // Alert.alert("GPS OK");
       
        Location.start();    
        console.log(success); // success => {alreadyEnabled: false, enabled: true, status: "enabled"}
    }.bind(this)).catch((error) => {
        console.log(error.message); // error.message => "disabled"
        Location.stop();

    });



   
}

componentWillUnmount(){

    Location.stop();

    this.listener.remove();

    LocationServicesDialogBox.forceCloseDialog();


    //Alert.alert("Quit");
}

getMachineNearMe(lon,lat,distance){

    if(lon==undefined||lat==undefined)
    {
       // Alert.alert('请打开定位!');

        lon=31.9083466555;
        lat=117.54;
       

    }

    let url=SERVER+"/machine/getAllNearMe";
    let data={"lon":lon,"lat":lat,"distance":distance};
    
   if(this.props.Net.NetWorkOK){

        NET.post(url,data,(res)=>{

            if(res.status=='100'){
            

                // if(res.data)
                console.log(res.data.length); 
                if(res.data.length>0)
                {
                    this.setState({points:res.data});

                }else{
                    this.getMachineByCity(this.city);

                }            


                
            }else
            {
               // Alert.alert('获取附近仪器失败');
               Toast.show("获取附近仪器失败")

            }

        });


   }else{
       Toast.show("无网络连接，请连接网络")

   }
    
}
     

getMachineByCity(city){

    if(city==undefined)
    {
        //Alert.alert('请打开定位!');
         city="合肥市"
    }
    let url=SERVER+"/machine/getAllByCity";
    let data={"city":city};

    if(this.props.Net.NetWorkOK){

        NET.post(url,data,(res)=>{
            if(res.status=='100'){
               
                if(res.data.length<=0)
                {
                    Toast.show("当前城市没有运营")
                }else{
                    this.setState({points:res.data});

                }
    
            }else
            {
                //Alert.alert('获取当前城市仪器失败');
                Toast.show("没有找到检测仪器,可能当前城市没有运营商")
            }
    
        });    
   
    }else{
        Toast.show("无网络连接，请连接网络")
 
    }

   
}


handlerLinkBaidu() {
    /* navi 驾车导航，bikenavi 骑行导航， walknavi步行导航
     * location 和 query 二填一
     * location 目的地经纬度 格式：location=40.057406655722,116.2964407172 (先纬度，后经度)
     * query 目的地名称
     */

     var tar="location="+this.targetLat+","+this.targetLon;
    let url = "baidumap://map/navi?"+tar;
    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
        //console.log('请先下载百度地图');
        Toast.show("请先下载百度地图");

      } else {
        return Linking.openURL(url);
      }
    }).catch(err => console.error('An error occurred', err));
  }
  handlerLinkGaode() {
    /* navi 导航  keywordNavi关键字导航
     * sourceApplication 第三方调用应用名称
     * dev 起终点偏移
     * lat 终点纬度
     * lon 终点经度
     * poiname 终点POI名称
     * keyword 终点关键词
     * style 导航方式(0 速度快; 1 费用少; 2 路程短; 3 不走高速；4 躲避拥堵；5 不走高速且避免收费；6 不走高速且躲避拥堵；7 躲避收费和拥堵；8 不走高速躲避收费和拥堵)
     */
    
    
     var msg="百度坐标:Lon"+this.targetLon+"Lat:"+this.targetLat;
     console.log(msg);

     let geoResult=NaviCtl.bd2gd(this.targetLon,this.targetLat);

     msg="高德坐标:"+geoResult;
     console.log(msg);

    let url = "androidamap://navi?sourceApplication=appname&lon="+geoResult.lng+"&lat="+geoResult.lat+"&dev=0&style=2"
    console.log(url);

    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
       // console.log('请先下载高德地图');
       // Alert.alert('请先下载高德地图');
       Toast.show("请先下载高德地图");
      } else {
          console.log(url);
        return Linking.openURL(url);
      }
    }).catch(err => console.error('An error occurred', err));
  }
    
 _onItemPress = point => {
          let message=this._points.indexOf(point).toString()+"导航到该地点";
          //Alert.alert(message);
        }

  _renderItem = ({ item }) =>
      
    <Text style={styles.logText}>{item.time} 当前时速:{item.data}Km/h</Text>
      
    
    render(){




        let makers = this.state.points.map((item,i) => {

            
           var status="空闲",type="尿常规检测",colortmp;
            switch(item.status)
            {
                case -1:
                status="故障";
                colortmp="#FB0202"
                break;

                case 1:
                status="正在使用";
                colortmp="#F8B03D"
                break;

                case 0:
                status="空闲";
                colortmp="#06F62A"
                break;
              
                default:
                status="空闲";
                colortmp="#06F62A"
                
                 

            }

            switch(item.checktype)
            {
                case 1:
                type="尿常规检测";
                break;

                case 2:
                type="无创血液检测";
                break;

                case 3:
                type="排卵检测";
                break;
                case 4:
                type="早孕检测";
                break;

                case 1234:
                type="尿常规检测、无创血液检测、排卵检测、早孕检测";
                break;
                case 12:
                type="尿常规检测、无创血液检测";
                break;
                case 123:
                type="尿常规检测、无创血液检测、排卵检测";
                break;
                case 234:
                type="无创血液检测、排卵检测、早孕检测";
                break;
                case 23:
                type="无创血液检测、排卵检测";
                break;
                case 24:
                type="无创血液检测、早孕检测";
                break;
                case 13:
                type="尿常规检测、排卵检测";
                break;
                case 14:
                type="尿常规检测、早孕检测";
                break;
                case 34:
                type="排卵检测、早孕检测";
                break;
                default:
                type="未知";
            }
            return <Marker
                key={item.creattime}
                selected
                title={`仪器序列号:${item.serialnumber}`}
                tinycolor='blue'
                //image="flag"
                description={"地址:"+item.locatename}
                coordinate={{
                latitude:item.lat,
                longitude:item.lon,
                }} 
                onPress={()=>{ 
                    this.targetLat=item.lat;
                    this.targetLon=item.lon;

                    this.setState({isNaviShow:true});
                    // console.log('click')

                }}  
                
               > 

                <Callout onPress={()=>{
                     this.targetLat=item.lat;
                     this.targetLon=item.lon;
                    //  console.log('click2')
 
                     this.setState({isNaviShow:true});


                }}>
                    <View style={{backgroundColor:"rgba(255,255,255,1)",borderWidth:1,borderRadius:4}}>

                        <View style={{flexDirection:'row'}}>
                                <Text style={{fontWeight:'bold'}}>序列号:</Text>
                                <Text>{item.serialnumber}</Text> 
                        </View> 
                        <View style={{flexDirection:'row'}}>
                                <Text style={{fontWeight:'bold'}}>状态:</Text>
                                <Text style={{color:`${colortmp}`}}>{status}</Text> 
                        </View>
                        <View style={{flexDirection:'row'}}>
                                <Text style={{fontWeight:'bold'}}>检测类型:</Text>
                                <Text>{type}</Text> 
                        </View>
                        <View style={{flexDirection:'row'}}>
                                <Text style={{fontWeight:'bold'}}>地址:</Text>
                                <Text >{item.locatename}</Text> 
                        </View>
                        
                    </View>

                </Callout>



               </Marker>
          })


          let naviELe=this.state.isNaviShow?
          <TouchableOpacity style={{position:"absolute",alignSelf:"center",bottom:30,zIndex:1}}
          onPress={()=>{

            this.setState({isMoldeShow:true});

             }}>
                 <Image style={[styles.imageSmall]}                   
                    source={require('../../res/images/navi.png')}>
                 </Image>

         </TouchableOpacity> :null;


      var naviModel= <Modal style={{justifyContent: "flex-end",margin: 0}}
                        backdropOpacity={0.7}             // 不透明
                        isVisible={this.state.isMoldeShow}    // 根据isModal决定是否显示
                        onBackdropPress={()=>{
                             this.setState({isMoldeShow:false})
                            }}
                    >
                        <View style={{flex:1,flexDirection:"row",justifyContent:"center",position:"absolute",backgroundColor:"rgba(255,255,255,1)",bottom:0,height:100,width:"100%"}}>
                            {/* 关闭页面 */}
                            <TouchableOpacity style={styles.naviBut}
                                onPress={() => {{
                                    this.handlerLinkBaidu();
                                    this.setState({
                                        isMoldeShow:false
                                    })
                                }}}
                            >
                                <Image style={[styles.imageSmall2]}                   
                                    source={require('../../res/images/baidumap.png')}>
                                </Image>
                            </TouchableOpacity>
                            <View style={{width:20}}></View>

                            <TouchableOpacity style={styles.naviBut}
                                onPress={() => {{
                                    this.handlerLinkGaode();
                                    this.setState({
                                        isMoldeShow:false
                                    })
                                }}}
                            >
                                 <Image style={[styles.imageSmall2]}                   
                                    source={require('../../res/images/gaodemap.png')}>
                                 </Image>
                            </TouchableOpacity>


                        </View>

                    </Modal>;
return  <View style={styles.body}> 
                     <View style={styles.navBarStyle}>
                            <Text style={[styles.navTitleStyle]}>
                                 附近仪器
                            </Text>
                     </View>

                     <MapView
                        ref={ref => this.mapView = ref}
                        style={styles.body2}
                       center={{ latitude: this.state.lastlat, longitude: this.state.lastlon }}
                        zoomLevel={12}
                        locationMode="follow"//locationMode?: 'normal' | 'follow' | 'compass'
                        locationEnabled
                        location={this.glocation}
                        center={this.glocation}

                    >
                     {makers}
                    </MapView>
                                    
                  

                     {/* <Text style={{position:"absolute",top:90,zIndex:1}}> 当前时速：{this.state.speed*3.6} Km/h</Text> */}
                     <TouchableOpacity style={{position:"absolute",top:30,right:10,zIndex:1}}
                      onPress={()=>{
                        this.zoomLevel=18;
                      // Geolocation.start();
                       let lat,lon,zoom;

                       if(this.lastLat==undefined||this.lastLon==undefined)
                       {
                             lat=this.state.lastlat;
                             lon=this.state.lastlon;
                             zoom=10;

                       }else{
                           lat=this.lastLat;
                           lon=this.lastLon;
                           zoom=18;
                       }
                       this.mapView.setStatus({zoomLevel:16,center:this.glocation}, 1000)
                     
                      this.getMachineNearMe(this.lastLon,this.lastLat,5);                 
                         }}>
                             <Image style={[styles.imageSmall]}                   
                                source={require('../../res/images/nearme2.png')}>
                             </Image>

                     </TouchableOpacity>

                     {naviELe}
                     {naviModel}
    </View>
   
    
    
    }

}



const styles = StyleSheet.create({
    body: {
      flex: 1,
     // bottom:25
    },
    imageSmall:{
        height:80,
        width:80,
        resizeMode:'contain',
        alignSelf: 'center',
       
    },
    imageSmall2:{
        height:60,
        width:60,
        resizeMode:'contain',
        alignSelf: 'center',
       
    },
    body2: {
        
       flex:1,
    //   width:"100%",
    //   height:"100%",
      marginBottom:50,
       
       
      },
       navBarStyle:{ // 导航条样式
        height:50,
        backgroundColor:'rgb(30,70,125)',
        // 设置主轴的方向
        flexDirection:'row',
        // 垂直居中 ---> 设置侧轴的对齐方式
        alignItems:'center',
        justifyContent:'center'
    },
    navTitleStyle: {
        color:'white',
        fontSize:16,
        top:10
    },
    naviBut:{
     alignSelf: 'center',
     alignContent: 'center',
    //  width:100,
    //  height:30,
    // borderWidth: .5,
    // borderRadius: 5,
    // backgroundColor:"rgb(79,149,223)"
    },
    navitxt:{
        color:"white",
        fontSize: 20,
        fontWeight: 'bold',
        alignSelf: 'center',


    },
    logs: {
       flex:1,
      elevation: 4,
      backgroundColor: '#fff',
    },
    logText: {
      paddingLeft: 15,
      paddingRight: 15,
      paddingTop: 10,
      paddingBottom: 10,
    },

    label:{
        position:'absolute',

    }

  })


function mapstates(state) 
{
    const {Net}=state
    return {
        Net
    }
    
}

export default connect(mapstates)(map);